import {
    getNextRoute,
    getTagNavListFromLocalstorage,
    getRouteTitleHandled,
    setTagNavListInLocalstorage,
    routeEqual,
    routeHasExist
} from "@/util";

import config from '@/config'
import router from '@/router'

const { homeName } = config

/* 关闭页面 */
const closePage = (state, route) => {
    const nextRoute = getNextRoute(state.tagNavList, route)
    state.tagNavList = state.tagNavList.filter(item => {
        return !routeEqual(item, route)
    })
    router.push(nextRoute)
}

export default {
    state: {
        tagNavList: [], //导航面包屑
        width_s: document.documentElement.clientWidth
    },
    getters: {
    },
    actions: {},
    mutations: {
        // 设置导航面包屑
        setTagNavList(state, list) {
            let tagList = []
            if (list) {
                tagList = [...list]
            } else tagList = getTagNavListFromLocalstorage() || []
            if (tagList[0] && tagList[0].name !== homeName) tagList.shift()
            let homeTagIndex = tagList.findIndex(item => item.name === homeName)
            if (homeTagIndex > 0) {
                let homeTag = tagList.splice(homeTagIndex, 1)[0]
                tagList.unshift(homeTag)
            }
            state.tagNavList = tagList
            setTagNavListInLocalstorage([...tagList])
        },
        // 关闭导航面包屑
        closeTag(state, route) {
            let tag = state.tagNavList.filter(item => routeEqual(item, route));
            route = tag[0] ? tag[0] : null;
            if (!route) return;
            closePage(state, route);
        },
        // 添加导航面包屑
        addTag(state, { route, type = 'unshift' }) {
            let router = getRouteTitleHandled(route)
            if (!routeHasExist(state.tagNavList, router)) {
                if (type === 'push') state.tagNavList.push(router)
                else {
                    if (router.name === homeName) state.tagNavList.unshift(router)
                    else state.tagNavList.splice(1, 0, router)
                }
                setTagNavListInLocalstorage([...state.tagNavList])
            }
        },
    }
};
